package com.yy.finvideoplayer.media

import android.content.Context
import android.webkit.URLUtil
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.PlaybackParameters
import com.google.android.exoplayer2.SeekParameters
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.dash.DashMediaSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSource
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.util.Util
import java.net.URLConnection.setDefaultRequestProperty

class ExoMedia(iMediaCallback: IMediaCallback) : ExoBaseMedia(iMediaCallback) {

    override fun createMediaSource(
        context: Context,
        url: String,
        headers: Map<String, String?>?
    ): MediaSource? {
        val dataSourceFactory = createDataSourceFactory(context, headers)
        return when {
            URLUtil.isNetworkUrl(url) && url.contains(".m3u8") -> {
                HlsMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(url))
            }
            URLUtil.isNetworkUrl(url) && (url.contains(".mpd") || url.contains(".dash")) -> {
                DashMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(url))
            }
            else -> {
                ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(MediaItem.fromUri(url))
            }
        }
    }

    private fun createDataSourceFactory(
        context: Context,
        headers: Map<String, String?>?
    ): DefaultDataSource.Factory {
        val upstreamFactory = DefaultHttpDataSource.Factory().apply {
            setUserAgent(Util.getUserAgent(context, "FinVideoPlayer"))
            headers?.forEach { (key, value) ->
                if (value != null) setDefaultRequestProperty(key, value)
            }
        }
        return DefaultDataSource.Factory(context, upstreamFactory)
    }

    override fun setSpeed(rate: Float): Boolean {
        player?.playbackParameters = PlaybackParameters(rate)
        return true
    }

    override fun createPlayer(context: Context): ExoPlayer {
        return ExoPlayer.Builder(context)
            .setSeekParameters(SeekParameters.EXACT) // 精确seek
            .build()
    }
}